package br.edu.ufcg.dsc.ia1.jt.core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import javax.imageio.ImageIO;

import org.neuroph.core.NeuralNetwork;
import org.neuroph.core.exceptions.VectorSizeMismatchException;
import org.neuroph.core.learning.SupervisedTrainingElement;
import org.neuroph.core.learning.TrainingSet;

import br.edu.ufcg.dsc.ia1.jt.util.RasterAsLine;

public class Train {
	
	NeuralNetwork neuralNet;
	
	public Train(NeuralNetwork neuralNetwork) {
		this.neuralNet = neuralNetwork;
	}
	
	public Train(String neuralNet) {
		this(NeuralNetwork.load(neuralNet));
	}
	
	public SupervisedTrainingElement extractTrainingElement(String line) throws IOException {
		Scanner sc = new Scanner(line);
		int ch = sc.nextInt(); //caractere
		double font = sc.nextDouble(); //fonte ID como em fontIDmap.txt
		String path = sc.next(); //caminho pra imagem
		//TODO: Tirar essa configuração de iamgem 20x20 hardcoded
		RasterAsLine asLine = new RasterAsLine(ImageIO.read(new File(path)), 20, 20, 1);
		return new SupervisedTrainingElement(asLine.line(), new double[]{ch, font});
	}
	
	public void train(String trainSet) {
		TrainingSet trainingSet = new TrainingSet();
		try {
			Scanner sc = new Scanner(new File(trainSet));
			while(sc.hasNextLine()) {
				//Para cada linha cria um SupervisedTrainingElement
				trainingSet.addElement(this.extractTrainingElement(sc.nextLine()));
			}
			this.neuralNet.learnInSameThread(trainingSet);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (VectorSizeMismatchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	}

}
